package day06;

import java.util.concurrent.atomic.AtomicInteger;

public class Demo04 {
    static AtomicInteger n = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        /*
         * 使用 原子整数方案(乐观锁方案)
         */
        Object lock = new Object();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                long t1 = System.nanoTime();
                for (int i=0; i<20000; i++) {
                    n.getAndIncrement(); //n++
                    //n.incrementAndGet(); //++n
                }
                long t2 = System.nanoTime();
                System.out.println("T1 OK:"+(t2-t1));
            }
        };
        t1.start();
        Thread t2 = new Thread(){
            @Override
            public void run() {
                long t1 = System.nanoTime();
                for (int i=0; i<20000; i++) {
                    n.getAndIncrement();
                }
                long t2 = System.nanoTime();
                System.out.println("T2 OK:"+(t2-t1));
            }
        };
        t2.start();
        Thread t3 = new Thread(){
            @Override
            public void run() {
                long t1 = System.nanoTime();
                for (int i=0; i<20000; i++) {
                    n.getAndIncrement();
                }
                long t2 = System.nanoTime();
                System.out.println("T3 OK:"+(t2-t1));
            }
        };
        t3.start();
        Thread.sleep(1000);
        System.out.println(n);
    }
}
